import 'dart:collection';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/album_service.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/models/upload_photo_model.dart';
import 'package:flutter_oldman_health/utils/event_bus.dart';
import "package:images_picker/images_picker.dart";

class UploadingPhotos {
  static bool upLoading = false;
  String lastAlbumId;

  static LinkedHashMap<String, UploadingPhotosInfo> _photoAlbumMap =
      LinkedHashMap();

  // factory UploadingPhotos() => _getInstance();
  //
  // static UploadingPhotos get instance => _getInstance();
  //
  // UploadingPhotos._internal() {
  //   // 创建对象
  //   _instance = UploadingPhotos();
  // }
  //
  // static UploadingPhotos _getInstance() {
  //   if (_instance == null) {
  //     _instance = UploadingPhotos._internal();
  //   }
  //   return _instance;
  // }
  UploadingPhotos._init();

  static final UploadingPhotos _instance = UploadingPhotos._init();

  factory UploadingPhotos() => _instance;

  // 1 上传时 要上传新的照片到正在上传中的相册
  // 2 上传时 要上传新的照片到已经完成上传的相册
  // 3 同步问题

  int addUpLoadPhoto(String albumId, List<Media> mediaList) {
    // _photoAlbumMap.putIfAbsent(albumId, () => mediaList);
    if (mediaList.isEmpty) {
      EasyLoading.showInfo("请添加照片");
      return -1;
    }
    if (null != _photoAlbumMap[albumId] &&
        !_photoAlbumMap[albumId].mediaList.isNotEmpty) {
      EasyLoading.showInfo("请上传结束后再上传图片");
      return 0;
    } else if (null != _photoAlbumMap[albumId]) {
      _photoAlbumMap[albumId].mediaList = mediaList;
      lastAlbumId = albumId;
      return 1;
    } else {
      _photoAlbumMap[albumId] =
          UploadingPhotosInfo(mediaList); //, mediaList.last.path
      lastAlbumId = albumId;
      return 1;
    }
  }

  // //多线程
  // upLoadPhoto2() async {
  //   // bool upload = await ISOManager.loadBalanceFuture<bool, int>(upLoadPhoto, 1);
  //   // int upload = await ISOManager.loadBalanceFuture<int,
  //   //         LinkedHashMap<String, UploadingPhotosInfo>>(
  //   //     upLoadPhoto, _photoAlbumMap);
  //   upLoadPhoto();
  //   // int upload =
  //   //     await ISOManager.loadBalanceFuture<int, int>(asyncCountEven, 11111111);
  //   // ReceivePort port = ReceivePort();
  //   // Isolate iso = await Isolate.spawn(upLoadPhoto2(), port.sendPort);
  //   // port.listen((message) {
  //   //   print(message);
  //   //   port.close();
  //   //   iso.kill();
  //   // });
  //   // sleep(Duration(seconds: 1));
  //   print('上传完毕结束咯 ');
  // }

  //耗时工作，计算偶数个数
  Future<int> asyncCountEven(int num) async {
    int count = 0;
    while (num > 0) {
      if (num % 2 == 0) {
        count++;
      }
      num--;
    }
    // upLoadPhoto2();
    return count;
  }

  upLoadPhoto() async {
    upLoading = true;

    //遍历相册id
    _photoAlbumMap.keys.forEach((albumId) {
      int index = 0;
      int mediaListLength = 0;
      List<Media> mediaList = _photoAlbumMap[albumId].mediaList;
      if (null != mediaList && mediaList.length > 0) {
        mediaListLength = mediaList.length;
        //遍历照片
        mediaList.forEach((e) {
          //上传照片
          uploadPhotoByPath(e, albumId).then((value) {
            index++;
            print("path  ssss: $index  ${e.path}");
          }).whenComplete(() {
            if (index == mediaListLength) {
              EventBus().emit("UploadCallbackEvent", false);

              _photoAlbumMap.remove(albumId);
              upLoading = _photoAlbumMap.isNotEmpty;
              return 1;
            }
          });
        });
      }
      return 1;
    });
  }

  static Future<bool> uploadPhotoByPath(Media media, String albumId) async {
    print(media.path);
    print(media.thumbPath);
    var value = await AlbumService.uploadPhotoByPath(media.path);
    if (null != value && value.statusCode == 200) {
      UploadPhotoModel uploadPhotoModel = UploadPhotoModel.fromJson(value.data);
      if (uploadPhotoModel.success()) {
        UploadPhoto uploadPhoto = uploadPhotoModel.data;
        String photoId = await savePhotoInfo(uploadPhoto, albumId);
        if (photoId != null) {
          print("photoId ssss: $photoId ");
        }
        return true;
      } else {
        EasyLoading.showInfo("上传照片失败");
        return true;
      }
    } else {
      EasyLoading.showInfo("上传照片失败");
      return true;
    }
  }

  //把照片添加到相应的相册
  static Future<String> savePhotoInfo(
      UploadPhoto uploadPhoto, String albumId) async {
    var value = await AlbumService.savePhotoInfo(
        uploadPhoto.filename, albumId, 1, uploadPhoto.path);
    if (null != value && value.statusCode == 200) {
      ResponseDataModel<String> responseDataModel =
          ResponseDataModel.fromJson(value.data);
      if (responseDataModel.success()) {
        return responseDataModel.data;
      } else {
        EasyLoading.showInfo(responseDataModel.msg);
        return null;
      }
    } else {
      EasyLoading.showInfo("添加照片到相册失败");
    }
    return null;
  }
}

class UploadingPhotosInfo {
  //可以改为栈
  List<Media> _mediaList = [];
  String _lastMediaPath;

  UploadingPhotosInfo(this._mediaList) {
    _lastMediaPath = _mediaList.last.path;
  }

  List<Media> get mediaList => _mediaList;

  set mediaList(List<Media> value) {
    _mediaList = value;
  }

  String get lastMediaPath => _lastMediaPath;
}
